package org.cloud.jiangyougateway.filter;
import lombok.extern.slf4j.Slf4j;
import org.cloud.jiangyoucommon.utils.StringUtils;
import org.cloud.jiangyougateway.utils.JwtTokenUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author mengpeng
 * @description token过滤器
 * @date 2019/12/12 13:55
 */
@Slf4j
@Component
@Order(-1)
public class LoginTokenFilter implements GlobalFilter, Ordered {

    private static final String AUTHORIZE_TOKEN = "Authorization";
    private static final String BEARER = "Bearer ";

    /**
     * token过滤
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("当前环境已开启token校验");
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        ServerHttpResponse response = exchange.getResponse();
        RequestPath path = request.getPath();
        if (path.toString().contains("/v2/api-docs")) {
            return  chain.filter(exchange);
        }
        // 取Authorization
        String tokenHeader = headers.getFirst(AUTHORIZE_TOKEN);
        log.info("tokenHeader=" + tokenHeader);
        // token不存在
        if (StringUtils.isEmpty(tokenHeader)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 取token
        String token = this.getToken(tokenHeader);
        log.info("token=" + token);

        // token不存在
        if (StringUtils.isEmpty(token)) {
            log.info("token不存在");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 校验 token是否失效
        if (JwtTokenUtils.isTokenExpired(token)) {
            log.info("token失效");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 校验 token是否正确
        if (!JwtTokenUtils.checkToken(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 有token 这里可根据具体情况，看是否需要在gateway直接把解析出来的用户信息塞进请求中，我们最终没有使用
//        UserTokenInfo userTokenInfo = UserTokenTools.getUserTokenInfo(token);
//        log.info("token={},userTokenInfo={}",token,userTokenInfo);
//        request.getQueryParams().add("token",token);
//        request.getHeaders().set("token", token);
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return -10;
    }

    /**
     * 解析Token
     */
    public String getToken(String requestHeader) {
        //2.Cookie中没有从header中获取
        if (requestHeader != null && requestHeader.startsWith(BEARER)) {
            return requestHeader.substring(7);
        }
        return "";
    }
}